package com.xucy.springboot.common;

/**
 * @Author xucy
 * @Date 2019-03-27 12:14
 * @Description
 **/

public class MyLinkedList {

    private LinkedNode first;

    MyLinkedList() {
        first = null;
    }

    /**
     * 插入新节点
     *
     * @param
     * @return
     * @Author xucy
     * @Date 12:15 2019-03-27
     */
    public void insertFirst(long value) {
        LinkedNode code = new LinkedNode(value);

        code.next = first;
        first = code;
    }

    /**
     * 删除节点
     *
     * @param
     * @return
     * @Author xucy
     * @Date 13:43 2019-03-27
     */
    public LinkedNode remove() {
        LinkedNode temp = first;
        first = temp.next;

        return temp;
    }

    /**
     * 判断是否为空
     *
     * @param
     * @return
     * @Author xucy
     * @Date 13:50 2019-03-27
     */
    public boolean isEmpty() {
        return first == null;
    }

    /**
     * 展示链表数据
     *
     * @param
     * @return
     * @Author xucy
     * @Date 12:17 2019-03-27
     */
    public void display() {
        LinkedNode code = first;
        while (code != null) {
            code.display();
            code = code.next;
        }
    }

    /**
     * 查找数据是否存在
     *
     * @param
     * @return
     * @Author xucy
     * @Date 14:03 2019-03-27
     */
    public boolean isFind(long value) {
        LinkedNode node = first;
        while (node.data != value) {
            if (node.next == null) {
                return false;
            }
            node = node.next;
        }

        return true;
    }

    /**
     * 删除链表中的某个值
     *
     * @param
     * @return
     * @Author xucy
     * @Date 14:40 2019-03-27
     */
    public boolean removeOne(long value) {
        LinkedNode current = first;
        LinkedNode pre = first;

        while (current.data != value) {
            if (current.next == null) {
                return false;
            }
            pre = current;
            current = current.next;
        }

        if (current == first) {
            first = first.next;
        } else {
            pre.next = current.next;
        }
        return true;
    }

    public static void main(String[] args) {
        MyLinkedList linkedList = new MyLinkedList();
        System.out.println(linkedList.isEmpty());

        linkedList.insertFirst(12);
        linkedList.insertFirst(23);
        linkedList.insertFirst(42);
        linkedList.insertFirst(45);
        linkedList.insertFirst(27);
        System.out.println(linkedList.isFind(42));
//        linkedList.display();

        linkedList.removeOne(23);
        linkedList.removeOne(45);
        linkedList.removeOne(27);
        linkedList.removeOne(12);
        System.out.println(linkedList.isEmpty());
        linkedList.display();
    }
}
